package net.guerlab.smart.wx.web.controller.user.wx.ma;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.error.WxErrorException;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.platform.user.api.OperationLogApi;
import net.guerlab.smart.platform.user.auth.UserContextHandler;
import net.guerlab.smart.wx.core.message.WxMaSubscribeMessageSendRequest;
import net.guerlab.smart.wx.service.controller.ma.AbstractWxMaSubscribeMsgController;
import net.guerlab.smart.wx.web.domain.WxMaSubscribeTemplateListResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

/**
 * 微信-小程序-订阅消息
 *
 * @author guer
 */
@Api(tags = "微信-小程序-订阅消息")
@RestController("/user/wx/ma/subscribeMsg")
@RequestMapping("/user/wx/ma/subscribeMsg")
public class SubscribeMsgController extends AbstractWxMaSubscribeMsgController {

    private static final String GET_TEMPLATE_URL = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate";

    private OperationLogApi operationLogApi;

    @ApiOperation("获取列表")
    @GetMapping("/{appId}/templateList")
    public List<WxMaSubscribeTemplateListResult.TemplateItem> list(
            @ApiParam(value = "应用ID", required = true) @PathVariable String appId) {
        try {
            String responseText = maManagerService.getService(appId).get(GET_TEMPLATE_URL, "");
            WxMaSubscribeTemplateListResult result = WxMaSubscribeTemplateListResult.fromJson(responseText);
            return result.getData();
        } catch (WxErrorException e) {
            throw new ApplicationException(e.getError().getErrorMsg(), e.getError().getErrorCode());
        }
    }

    @Override
    protected void afterSendMsg(String appId, Collection<String> openIds, WxMaSubscribeMessageSendRequest request) {
        operationLogApi.add("发送微信小程序订阅消息", UserContextHandler.getUserId(), appId, openIds, request);
    }

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public void setOperationLogApi(OperationLogApi operationLogApi) {
        this.operationLogApi = operationLogApi;
    }
}
